#encoding:utf-8
from time import sleep
import random
from datetime import datetime
import os
import  uuid
from django.conf import urls,settings
from django.shortcuts import render,render_to_response,redirect
from django.template import Template,Context
from django.http import HttpResponse,HttpRequest

from django.contrib.auth import logout ,login ,authenticate
from django.core.urlresolvers import reverse  #通过视图函数反向解析url
from django.views.generic import View #通用视图的基类
from django.contrib.auth.models import Permission
from django.contrib.auth.decorators import permission_required
from books.models import *
from forms import *
from mysite_project import settings

class my_view(View):
    def get(self,request,*args,**kwargs):

        return HttpResponse('I am a class view')



def index(request):
    # print request.scheme #表示为请求方案 http or https
    # print request.body # 表示原始HTTP的正文 ？？？
    # print request.read()  #???
    # print request.path #表示不含域名的的url
    # print request.path_info #除去服务器的前置的前置信息
    # print request.method  #http的方法
    # print request.GET# or (POST) 返回 字典子类 querydict对象  方法有：get(key,fail_return_value)，__setitem__(key,value),update(other_dict)
    # print request.COOKIES #返回一个字典 包含cookies
    # print request.FILES #  返回一个字典 包含所有上传文件  FILES 中的每个键为<input type="file" name="" /> 中的name。
    # print request.META # 网页的头文件
    # print request.user #一个AUTH_USER_MODEL 的对象 ，没有是的匿名用户
    # print request.session # 网页会话 http://python.usyiyi.cn/django_182/topics/http/sessions.html
    # ##方法
    # print request.get_host() #返回主机的 ip 127.0.0.1
    # print request.get_full_path() # 返回绝对路径
    # #print request.readines() #???


    news_list = News.objects.all()
    news_list = random.sample(news_list,4)
    return render(request,'books/index.html',locals())

def my_login(request):
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid(): #验证以后才有cleaned_data属性
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = authenticate(username= username ,password = password) #返回User中的jin实例
            if user is not None:
                user.backend = 'django.contrib.auth.backends.ModelBackend' #指定认真的缓存 不然 login报错
                login(request,user)
                return redirect('/success/')
            else:
                login_form = LoginForm()
                fail_word = '登录失败 请核对密码重新登录'
                return render(request, 'books/my_login.html', locals())
    if request.method =="GET":
        login_form = LoginForm()
    return render(request, 'books/my_login.html', locals())

def reg(request):
    print 'here2'
    print request.method
    if request.method == "POST":
        regform = RegForm(request.POST,request.FILES)
        print regform.is_valid()
        if not regform.is_valid ():
            # username = regform.cleaned_data['username']
            # password = regform.cleaned_data['password']
            # user = User.objects.create_user(username =username,password =password)
            # user.save()
            # user.user_permissions = [Permission.objects.get(codename ='view' ),Permission.objects.get(codename ='create' ),] #添加权限
            # user.save()
            print 'here1'
            file = request.FILES.get('img',None)
            if file is not None:
                today = datetime.today()
                root_conf = os.path.join(settings.MEDIA_ROOT,'new_img/%s/%s/'%(today.year,today.month))
                name =str(uuid.uuid1())+'.jpeg'
                total_path = root_conf + name
                os.makedirs(root_conf)
                with open(total_path,'wb+') as fd:
                    for chunk in file.chunks(): #防止图片太大，内存溢出
                        fd.write(chunk)
            return redirect('/my_login/')
    if request.method =="GET":
        regform = RegForm()
    return render(request, 'books/reg.html', locals())

#@permission_required(perm = 'books.view',login_url ='/my_login/')
def personal_page(request):

    # if user.has_perm('books.view'): # <app label>.<permission codename>
    #     right = 'you have right to view '
    # else:
    #     right = 'you do not have right to view '

    return render(request, 'books/personal_page.html', locals())






